package top.infopub.mgr.bpa.vo;

import java.io.Serializable;

/**
 * Created by wurz on 2021/6/11.
 */
public class PageQuery<T> implements Serializable {
    private static final long serialVersionUID = 1365630128856068166L;

    private static final int DEFAULT_PAGE_INDEX = 1;// 默认当前页码

    private static final int DEFAULT_PAGE_SIZE = 20;// 默认每页记录数

    private static final int MAX_PAGE_SIZE = 10000;// 默认每页最大记录数
    // 当前页码
    private Integer pageIndex;

    private Integer pageSize = DEFAULT_PAGE_SIZE;// 每页大小

    private T queryParam;

    private Integer offset;

    private Integer limit;

    //用于兼容前端分页查询与后台不分页查询SQL
    private boolean isPage = true;

    public Integer getLimit() {
        return pageSize;
    }

    /**
     * 获取当前页码
     *
     * @return
     */
    public Integer getPageIndex() {
        if (pageIndex == null || pageIndex < 1) {
            return DEFAULT_PAGE_INDEX;
        }
        return pageIndex;
    }

    /**
     * 设置当前页码
     *
     * @param pageIndex
     */
    public void setPageIndex(Integer pageIndex) {
        this.pageIndex = pageIndex;
    }

    /**
     * 获取每页的记录数
     *
     * @return
     */
    public Integer getPageSize() {
        return pageSize;
    }

    /**
     * 设置每页的记录数
     *
     * @param pageSize
     */
    public void setPageSize(Integer pageSize) {
        if (pageSize > MAX_PAGE_SIZE) {
            this.pageSize = MAX_PAGE_SIZE;
        } else if (pageSize < 1) {
            this.pageSize = DEFAULT_PAGE_SIZE;
        } else {
            this.pageSize = pageSize;
        }
    }

    public Integer getOffset() {
        if (isPage){
            return (this.getPageIndex()-1) * this.getPageSize();
        }
        return this.offset;
    }

    public void setOffset(Integer offset) {
        this.offset = offset;
        if (offset != null){
            this.setPageIndex(offset/this.pageSize+1);
        }
    }

    /**
     * 获取记录的开始索引
     *
     * @return
     */
    public Integer getRecordIndex() {
        return getPageSize() * (getPageIndex() - 1);
    }

    public T getQueryParam() {
        return queryParam;
    }

    public void setQueryParam(T queryParam) {
        this.queryParam = queryParam;
    }

    public boolean isPage() {
        return isPage;
    }

    public void setPage(boolean page) {
        isPage = page;
    }
}
